package com.mvc.config;

import com.mvc.common.Res;
import com.mvc.common.ResultCode;
import com.mvc.common.excetion.AssertDataThrow;
import com.mvc.common.excetion.AssertThrow;
import com.mvc.common.excetion.FeignResponseException;
import com.mvc.common.excetion.ResThrow;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常处理
 * @author JayEinstein
 */
@RestControllerAdvice
@Slf4j
public class ExceptionAdvice {

    /**
     * Res异常
     * @param resThrow
     * @return
     */
    @ExceptionHandler(value = ResThrow.class)
    public Object resThrow(ResThrow resThrow) {
        return resThrow.getRes();
    }

    /**
     * 数据断点抛出
     * @param assertDataThrow
     * @return
     */
    @ExceptionHandler(value = AssertDataThrow.class)
    public Object assertDataThrow(AssertDataThrow assertDataThrow) {
        return Res.of(assertDataThrow.getStatusCode(), assertDataThrow.getData(), assertDataThrow.getMsg());
    }

    /**
     * 断点异常
     * @param assertThrow
     * @return
     */
    @ExceptionHandler(value = AssertThrow.class)
    public Object assertThrow(AssertThrow assertThrow) {
        return Res.of(assertThrow.getStatusCode(), assertThrow.getMsg());
    }

    /**
     * feign熔断异常
     * @param feignResponseException
     * @return
     */
    @ExceptionHandler(value = FeignResponseException.class)
    public Object feignResponseException(FeignResponseException feignResponseException) {

        int statusCode = feignResponseException.getStatusCode();
        // 超时
        if (statusCode == FeignResponseException.Code.TIMEOUT) {
            return Res.of(ResultCode.TIMEOUT, feignResponseException.getMessage());
        }

        // 负载均衡异常
        if (statusCode == FeignResponseException.Code.CLIENT_ERROR) {
            return Res.of(ResultCode.BUSY, feignResponseException.getMessage());
        }

        return Res.error(feignResponseException);
    }

    /**
     * 异常处理
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Object handleException(Exception ex) {

        log.error("程序出现异常", ex);

        return Res.error(ex);
    }

}
